<template>
  <div>
    <!-- 搜索框 -->
    <view class="header">
      <view class="goods-search">
        <icon class="goods-search-icon" type="search" size="14"/>
        <input v-model="searchVal" @confirm="confirmSearch" @input="handleInput" class="goods-search-in" confirm-type="search" placeholder="搜索"/>
        <span class="cancel" @tap="handleCancel" v-if="searchVal!==''">取消</span>
      </view>
    </view>

    <!-- 搜索历史 -->
    <div class="history-list">
      <div class="title">
        <span class="title-text">搜索历史</span>
        <icon class="title-icon" type="clear" size="16" @tap="delAll"></icon>
      </div>
      <div class="list">
        <div class="item" v-for="(item, index) of historyList" :key="index">
          <span class="keyword" @tap="tapTag(item)">{{item}}</span>
          <icon class="icon" type="cancel" size="14" @tap="delTag(index)"></icon>
        </div>
      </div>
    </div>

    <!-- 搜索建议 -->
    <scroll-view scroll-y class="qSearch" v-if="searchVal!==''">
      <div class="qs-list">
        <block v-for="item of qSearchList" :key="item.goods_id">
          <div class="item" @tap="tapToList(item.goods_id)">{{item.goods_name}}</div>
        </block>
      </div>
    </scroll-view>

  </div>
</template>

<script>
import { qSearch } from '@/api'
import { setTimeout, clearTimeout } from 'timers';
export default {
  data () {
    return {
      n: 0,
      searchVal: '', // 搜索的内容
      historyList: [], // 搜索历史
      qSearchList: [], // 建议搜索列表
      qsObj: {} // 搜索对象
    }
  },
  // 小程序页面加载事件
  onLoad () {
    this.historyList = wx.getStorageSync('history-list') || [];
  },
  methods: {
    // 取消按钮
    handleCancel () {
      this.searchVal = ''
    },
    // 删除所有历史
    delAll () {
      wx.removeStorageSync('history-list');
    },
    // 删除单个历史
    delTag (index) {
      console.log(index)
      this.historyList.splice(index, 1)
      wx.setStorageSync('history-list',this.historyList)
    },
    // 输入时
    handleInput (e) {
      this.qsObj = { query: e.target.value}
      let fn = this.throttle(this.qsearch, 400, 500)
      fn();
    },
    // 搜索
    qsearch () {
      // let qsObj = { query: e.target.value}
      let qsObj = this.qsObj
      console.log('执行：', this.n++)
      qSearch(qsObj).then(res => {
        // console.log(res)
        this.qSearchList = res.message
      })
    },
    // 确认搜索
    confirmSearch () {
      // 将搜索结果保存进数组
      this.historyList.unshift(this.searchVal);
      // 利用 ES6 的 set 的特性对数组去重，然后再将其展开至数组中
      this.historyList = [...new Set(this.historyList)];
      // 将搜索历史储存回本地
      wx.setStorageSync('history-list',this.historyList)
      // 点击搜索确认后跳转到商品详情页面
      wx.navigateTo({ url: '/pages/goodslist/main?query=' + this.searchVal });
    },
    // 点击建议搜索, 跳转详情页面
    tapToList (id) {
      wx.navigateTo({ url: '/pages/goodsdetail/main?goods_id=' + id });
    },
    // 点击tag搜索
    tapTag (keyword) {
      wx.navigateTo({ url: '/pages/goodslist/main?query=' + keyword });
    },

    // 节流函数，避免频繁发起请求
    throttle (fn, delay, duration) {
      var timer = null // 定时器id
      var begin = new Date()
      return function () {
        var context = this // 保存this
        var args = arguments // apply 需要
        var current = new Date()
        console.log(current - begin , duration, delay)
        // console.log(timer)
        clearTimeout(timer) // 清除定时器
        if (current - begin >= duration) { // 时间间隔
          fn.apply(context, args)
          begin = current
        } else {
          timer = setTimeout(function(){
            fn.apply(context, args)
          }, delay)
          console.log(timer)
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
// 搜索框
.header {
  color: #666;
  padding: 20rpx;
  // background-color: #f4f4f4;
  background-image:linear-gradient(45deg, #ed1c24, #ff9700);
  .goods-search {
    display: flex;
    background-color: #fff;
    border-radius: 10rpx;
    .goods-search-icon {
      display: block;
      width: 14rpx;
      height: 14rpx;
      padding: 15rpx 20rpx;
    }
    .goods-search-in {
      flex: 1;
      height: 50rpx;
      line-height: 50rpx;
      font-size: 26rpx;
      padding: 0 20rpx;
    }
    .cancel {
      padding: 0 20rpx;
      color: #fff;
      background-color: #f76210;
      font-size: 26rpx;
      height: 52rpx;
      line-height: 52rpx;
      border-top-right-radius: 10rpx;
      border-bottom-right-radius: 10rpx;
    }
  }
}

// 搜索历史
.history-list {
  padding: 20rpx;
  font-size: 24rpx;
  .title {
    display: flex;
    justify-content: space-between;
    background-color: #fff;
    // 实现纸张翘角效果, 通过伪元素实现阴影效果
    position: relative;
    &::before, &::after {
      content: '';
      position: absolute;
      top: 0;
      z-index: -1;
      width: 50%;
      height: 95%;
      box-shadow: 0 10rpx 10rpx #ccc;
    }
    &::before {
      transform: rotate(-2deg);
      transform-origin: top left;
      left: 10rpx;
    }
    &::after {
      transform: rotate(2deg);
      transform-origin: top right;
      right: 10rpx;
    }
    .title-text {
      padding: 10rpx 20rpx;
      color: #666;
      font-size: 28rpx;
      border-left: 10rpx solid #ff2d49;
    }
    .title-icon {
      padding: 10rpx;
    }
  }
  .list {
    margin-top: 20rpx;
    display: flex;
    flex-wrap: wrap;
    .item {
      padding: 10rpx 20rpx;
      margin: 10rpx;
      color: #fff;
      background-image:linear-gradient(45deg, #f7585e, #f7a934);
      position: relative;
      .icon {
        position: absolute;
        top: -10rpx;
        right: -10rpx;
        border-radius: 50%;
        background-color: #fff;
      }
    }
  }
}
// 搜索建议
.qSearch {
  background-color: #fff;
  position: fixed;
  top: 90rpx;
  left: 0;
  right: 0;
  bottom: 0;
  .qs-list {
    .item {
      padding: 20rpx;
      color: #888;
      font-size: 24rpx;
      border-bottom: 1rpx solid #eee;
      // 一行省略号
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
}
</style>
